package org.jeecg.modules.goods.goods.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.goods.goods.entity.EbizGoods;
import org.jeecg.modules.goods.goods.entity.Goods;
import org.jeecg.modules.goods.goods.mapper.GoodsMapper;
import org.jeecg.modules.goods.goods.service.IEbizGoodsService;
import org.jeecg.modules.goods.goods.service.IGoodsService;
import org.jeecg.modules.oss.service.IOssFileService;
import org.jeecg.modules.system.entity.SysCategory;
import org.jeecg.modules.system.service.ISysCategoryService;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.tplus.dto.InventoryQueryRepDto;
import org.jeecg.modules.tplus.dto.InventoryInfoReqDto;
import org.jeecg.modules.tplus.dto.InventoryEntityReqDto;
import org.jeecg.modules.tplus.service.DatabaseService;
import org.jeecg.modules.tplus.service.ITplusService;
import org.jeecg.modules.goods.util.S3Util;
import org.jeecg.modules.oss.entity.OssFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 产品信息
 * @Author: jeecg-boot
 * @Date: 2025-06-07
 * @Version: V1.0
 */
@Slf4j
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements IGoodsService {

    @Autowired
    private ISysDictService sysDictService;

    @Autowired
    @Lazy
    private ITplusService tplusService;

    @Autowired
    private IEbizGoodsService ebizGoodsService;
    @Autowired
    private ISysCategoryService sysCategoryService;
    @Autowired
    private IOssFileService ossFileService;

    @Autowired
    private S3Util s3Util;

    private static final String INVENTORY_IMAGE_URL = "https://prod-tplusoss-r-bj.oss-cn-beijing.aliyuncs.com/perm/attachment/1240206642277139/1240268964860881/aa/aa1022/pic/";

    /**
     * 从T+系统查询存货信息并保存或更新到本地数据库
     *
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @param createBy  创建人
     * @return 处理结果
     */
    public boolean syncInventoryFromTPlus(String startDate, String endDate, String createBy) {
        try {
            // 构建查询参数
            org.jeecg.modules.tplus.dto.InventoryQueryReqDto inventoryQueryReqDto = new org.jeecg.modules.tplus.dto.InventoryQueryReqDto();
            org.jeecg.modules.tplus.dto.InventoryQueryReqDto.InventoryQueryParam param = new org.jeecg.modules.tplus.dto.InventoryQueryReqDto.InventoryQueryParam();
            param.setUpdateDateBegin(startDate);
            param.setUpdateDateEnd(endDate);
            param.setPageIndex(1);
            param.setPageSize(100);
            inventoryQueryReqDto.setParam(param);

            int totalProcessed = 0;
            int currentPage = 1;
            boolean hasMoreData = true;

            while (hasMoreData) {
                param.setPageIndex(currentPage);

                // 调用T+系统查询存货接口
                org.jeecg.modules.tplus.dto.InventoryListQueryRepDto result = tplusService
                        .doInventoryQuery(inventoryQueryReqDto);

                if (result != null && result.getData() != null && !result.getData().isEmpty()) {
                    // 处理查询结果，保存或更新到本地数据库
                    for (org.jeecg.modules.tplus.dto.InventoryQueryRepDto inventoryDto : result.getData()) {
                        saveInventoryFromTPlus(inventoryDto, createBy);
                        totalProcessed++;
                    }

                    // 检查是否还有更多数据
                    if (result.getData().size() < param.getPageSize()) {
                        hasMoreData = false;
                    } else {
                        currentPage++;
                    }
                } else {
                    hasMoreData = false;
                }
            }

            log.info("从T+系统同步存货信息成功，时间范围: {} - {}，共处理 {} 条记录", startDate, endDate, totalProcessed);
            return true;
        } catch (Exception e) {
            log.error("从T+系统同步存货信息失败，时间范围: {} - {}，错误信息: {}", startDate, endDate, e.getMessage(), e);
            return false;
        }
    }

    /**
     * 从T+系统查询指定存货信息并保存或更新到本地数据库
     *
     * @param inventoryCode 存货编码
     * @param createBy      创建人
     * @return 处理结果
     */
    public boolean syncSingleInventoryFromTPlus(String inventoryCode, String createBy) {
        try {
            // 构建查询参数
            org.jeecg.modules.tplus.dto.InventoryQueryReqDto inventoryQueryReqDto = new org.jeecg.modules.tplus.dto.InventoryQueryReqDto();
            org.jeecg.modules.tplus.dto.InventoryQueryReqDto.InventoryQueryParam param = new org.jeecg.modules.tplus.dto.InventoryQueryReqDto.InventoryQueryParam();
            param.setCode(inventoryCode);
            param.setPageIndex(1);
            param.setPageSize(100);
            inventoryQueryReqDto.setParam(param);

            // 调用T+系统查询存货接口
            org.jeecg.modules.tplus.dto.InventoryListQueryRepDto result = tplusService
                    .doInventoryQuery(inventoryQueryReqDto);

            if (result != null && result.getData() != null && !result.getData().isEmpty()) {
                // 处理查询结果，保存或更新到本地数据库
                for (org.jeecg.modules.tplus.dto.InventoryQueryRepDto inventoryDto : result.getData()) {
                    saveInventoryFromTPlus(inventoryDto, createBy);
                }
                log.info("从T+系统同步单个存货信息成功，存货编码: {}", inventoryCode);
                return true;
            } else {
                log.warn("从T+系统未查询到存货信息，存货编码: {}", inventoryCode);
                return false;
            }
        } catch (Exception e) {
            log.error("从T+系统同步单个存货信息失败，存货编码: {}，错误信息: {}", inventoryCode, e.getMessage(), e);
            return false;
        }
    }

    /**
     * 将T+存货信息转换并保存到cg_goods表
     *
     * @param inventoryDto T+存货信息
     * @param createBy     创建人
     * @return 保存结果
     */
    public boolean saveInventoryFromTPlus(InventoryQueryRepDto inventoryDto, String createBy) {
        try {
            // 检查是否已存在相同编码的商品
            QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("goods_code", inventoryDto.getCode());
            Goods existingGoods = this.getOne(queryWrapper);

            Goods goods;
            if (existingGoods != null) {
                // 更新现有商品
                goods = existingGoods;
                goods.setUpdateBy(createBy);
                goods.setUpdateTime(new Date());
            } else {
                // 创建新商品
                goods = new Goods();
                goods.setId(UUIDGenerator.generate());
                goods.setCreateBy(createBy);
                goods.setCreateTime(new Date());
                goods.setUpdateBy(createBy);
                goods.setUpdateTime(new Date());
                goods.setTenantId(0);
            }

            // 基本信息映射
            goods.setGoodsCode(inventoryDto.getCode());
            goods.setGoodsName(inventoryDto.getName());
            goods.setGoodsNameCn(inventoryDto.getPriuserdefnvc1()); // 中文简称
            goods.setGoodsUnit(inventoryDto.getBaseUnitCode());
            // 存货描述
            goods.setGoodsDescribe(inventoryDto.getInventoryDescript());
            // 供应情况字典转换
            String supplySituationText = inventoryDto.getPriuserdefnvc11();
            String supplySituationCode = getDictValueByText("GYQK", supplySituationText);
            goods.setSupplySituation(supplySituationCode); // 供应情况

            // 分类信息
            if (inventoryDto.getInventoryClass() != null) {
                goods.setCategoryId(inventoryDto.getInventoryClass().getCode());
            }

            // 品牌
            // 品牌字典转换
            if (inventoryDto.getProductInfo() != null) {
                String brandCode = inventoryDto.getProductInfo().getCode();
                String brandText = getDictTextByValue("PP", brandCode);
                goods.setGoodsBrand(inventoryDto.getProductInfo().getCode()); // 品牌
            }

            // 将中文值转换为字典编码
            String logisticsText = inventoryDto.getPriuserdefnvc5();
            String logisticsCode = getDictValueByText("HDHHY", logisticsText);
            goods.setGoodsLogistics(logisticsCode); // 含电或含液

            // 构建产品信息JSON - 保留现有字段，只更新T+同步的字段
            Map<String, Object> goodsInfo = new HashMap<>();

            // 如果是更新操作，先获取现有的JSON数据
            if (existingGoods != null && existingGoods.getGoodsInfo() != null) {
                try {
                    String existingGoodsInfoStr = existingGoods.getGoodsInfo().toString();
                    if (oConvertUtils.isNotEmpty(existingGoodsInfoStr)) {
                        goodsInfo.putAll(JSON.parseObject(existingGoodsInfoStr));
                    }
                } catch (Exception e) {
                    log.warn("解析现有商品信息JSON失败，将创建新的JSON: {}", e.getMessage());
                }
            }

            // 更新基本信息字段
            goodsInfo.put("id", goods.getId());
            goodsInfo.put("goodsCode", inventoryDto.getCode());
            if (inventoryDto.getInventoryClass() != null) {
                goodsInfo.put("categoryId", inventoryDto.getInventoryClass().getCode());
                // goodsInfo.put("categoryPath", inventoryDto.getInventoryClass().getCode());
            }

            goodsInfo.put("goodsName", inventoryDto.getName());
            goodsInfo.put("goodsNameCn", inventoryDto.getPriuserdefnvc1());
            goodsInfo.put("goodsUnit", inventoryDto.getBaseUnitName());
            goodsInfo.put("isEshop", inventoryDto.getIsEshop());
            goodsInfo.put("isPurchase", inventoryDto.getIsPurchase());
            goodsInfo.put("isSale", inventoryDto.getIsSale());
            goodsInfo.put("isMadeSelf", inventoryDto.getIsMadeSelf());
            goodsInfo.put("isMaterial", inventoryDto.getIsMaterial());
            goodsInfo.put("isLaborCost", inventoryDto.getIsLaborCost());
            goodsInfo.put("isMadeRequest", inventoryDto.getIsMadeRequest());


            // 计价方式
            String valueTypeText = inventoryDto.getValueType().getCode();
            String valueTypeCode = getDictValueByText("JJFS", valueTypeText);
            goodsInfo.put("valueType", valueTypeCode); // 计价方式

            // 包装字典转换
            String packagingText = inventoryDto.getPriuserdefnvc4();
            String packagingCode = getDictValueByText("BZ", packagingText);
            goodsInfo.put("packaging", packagingCode); // 包装

            // 二级分类
            String categoryId_children = inventoryDto.getPriuserdefnvc3();
            String categoryId_children_code = getDictValueByText("EJFL", categoryId_children);
            goodsInfo.put("categoryId_children", categoryId_children_code);

            // 质量字典转换
            String qualityText = inventoryDto.getPriuserdefnvc9();
            String qualityCode = getDictValueByText("ZL", qualityText);
            goodsInfo.put("quality", qualityCode); // 质量

            // 材质/细分品牌字典转换
            String materialText = inventoryDto.getPriuserdefnvc10();
            String materialCode = getDictValueByText("XFPP", materialText);
            goodsInfo.put("productMaterial", materialCode); // 材质/细分品牌

            // 适配品牌字典转换
            // 适配品牌字典转换
            String compatibleBrandText = inventoryDto.getPriuserdefnvc7();
            String compatibleBrand = getDictValueByText("XH", compatibleBrandText);
            goodsInfo.put("compatibleBrand", compatibleBrand); // 适配品牌（使用已转换的值）
            // goodsInfo.put("compatibleBrandPath", brandText); // 适配品牌（使用已转换的值）
            goodsInfo.put("compatibleModel", inventoryDto.getPriuserdefnvc7()); // 型号

            // 供应情况字典转换
            goodsInfo.put("supplySituation", supplySituationCode); // 供应情况（使用已转换的值）

            // 性质字典转换
            String attributesText = inventoryDto.getPriuserdefnvc8();
            String attributesCode = getDictValueByText("XZ", attributesText);
            goodsInfo.put("inventoryAttributes", attributesCode); // 性质

            // 含电或含液字典转换（使用已转换的值）
            goodsInfo.put("infringementRisk", logisticsCode); // 含电或含液

            // 标签型号和标签质量转换存储
            String modelText = inventoryDto.getPriuserdefnvc7();
            String modelCode = getDictValueByText("BQXH", modelText);
            goodsInfo.put("labelModel", modelCode); // 标签型号（使用型号字段）

            // 品牌
            if (inventoryDto.getProductInfo() != null) {
                String brandCode = inventoryDto.getProductInfo().getCode();
                String brandText = getDictTextByValue("PP", brandCode);
                goodsInfo.put("goodsBrand", brandCode);
                goodsInfo.put("goodsBrandPath", brandText);
            }

            String labelQualityText = inventoryDto.getPriuserdefnvc9();
            String labelQualityCode = getDictValueByText("BQZL", labelQualityText);
            goodsInfo.put("labelQuality", labelQualityCode); // 标签质量（转换为字典编码）

            // 仓库信息
            if (inventoryDto.getWarehouse() != null) {
                goodsInfo.put("defaultWarehouse", inventoryDto.getWarehouse().getName());
                goodsInfo.put("defaultWarehouse_code", inventoryDto.getWarehouse().getCode());
            }

            // 货位信息
            if (inventoryDto.getInvlocation() != null) {
                goodsInfo.put("defaultLocation", inventoryDto.getInvlocation().getCode());
                goodsInfo.put("defaultLocation_code", inventoryDto.getInvlocation().getCode());
            }

            // 供货商信息
            if (inventoryDto.getPartner() != null) {
                goodsInfo.put("defaultSupplier", inventoryDto.getPartner().getName());
                goodsInfo.put("defaultSupplier_code", inventoryDto.getPartner().getCode());
            }

            goods.setGoodsInfo(JSON.toJSONString(goodsInfo));

            // 构建价格信息JSON - 保留现有字段，只更新T+同步的字段
            Map<String, Object> goodsPrice = new HashMap<>();

            // 如果是更新操作，先获取现有的价格信息JSON数据
            if (existingGoods != null && existingGoods.getGoodsPrice() != null) {
                try {
                    String existingGoodsPriceStr = existingGoods.getGoodsPrice().toString();
                    if (oConvertUtils.isNotEmpty(existingGoodsPriceStr)) {
                        goodsPrice.putAll(JSON.parseObject(existingGoodsPriceStr));
                    }
                } catch (Exception e) {
                    log.warn("解析现有商品价格信息JSON失败，将创建新的JSON: {}", e.getMessage());
                }
            }

            goodsPrice.put("id", goods.getId());
            goodsPrice.put("goodsCode", inventoryDto.getCode());
            goodsPrice.put("mainlandCost", inventoryDto.getPriuserdefdecm1()); // 大陆成本
            goodsPrice.put("hkCost", inventoryDto.getPriuserdefdecm2()); // 港币成本
            goodsPrice.put("hkProfitMargin", inventoryDto.getPriuserdefdecm4()); // 港币利润率
            goodsPrice.put("MainlandProfitMargin", inventoryDto.getPriuserdefdecm5()); // 大陆利润率
            goodsPrice.put("supplySituation", supplySituationCode); // 供应情况
            if (inventoryDto.getPartner() != null) {
                goodsPrice.put("supplier", inventoryDto.getPartner().getName());
                goodsPrice.put("supplier_code", inventoryDto.getPartner().getCode());
            }

            goods.setGoodsPrice(JSON.toJSONString(goodsPrice));

            // 构建英文资料JSON - 保留现有字段，只更新T+同步的字段
            Map<String, Object> goodsEnglish = new HashMap<>();

            // 如果是更新操作，先获取现有的英文资料JSON数据
            if (existingGoods != null && existingGoods.getGoodsEnglish() != null) {
                try {
                    String existingGoodsEnglishStr = existingGoods.getGoodsEnglish().toString();
                    if (oConvertUtils.isNotEmpty(existingGoodsEnglishStr)) {
                        goodsEnglish.putAll(JSON.parseObject(existingGoodsEnglishStr));
                    }
                } catch (Exception e) {
                    log.warn("解析现有商品英文资料JSON失败，将创建新的JSON: {}", e.getMessage());
                }
            }

            goodsEnglish.put("id", goods.getId());
            goodsEnglish.put("goodsCode", inventoryDto.getCode());
            goodsEnglish.put("englishName", inventoryDto.getSpecification()); // 英文名称
            goodsEnglish.put("englishShortName", inventoryDto.getPriuserdefnvc2()); // 英文简称
            goodsEnglish.put("websiteTitle", inventoryDto.getInventoryDescript());// 产品标题
            goods.setGoodsEnglish(JSON.toJSONString(goodsEnglish));

            // 构建发货信息JSON - 保留现有字段，只更新T+同步的字段
            Map<String, Object> goodsDeliver = new HashMap<>();

            // 如果是更新操作，先获取现有的发货信息JSON数据
            if (existingGoods != null && existingGoods.getGoodsDeliver() != null) {
                try {
                    String existingGoodsDeliverStr = existingGoods.getGoodsDeliver().toString();
                    if (oConvertUtils.isNotEmpty(existingGoodsDeliverStr)) {
                        goodsDeliver.putAll(JSON.parseObject(existingGoodsDeliverStr));
                    }
                } catch (Exception e) {
                    log.warn("解析现有商品发货信息JSON失败，将创建新的JSON: {}", e.getMessage());
                }
            }

            goodsDeliver.put("id", goods.getId());
            goodsDeliver.put("goodsCode", inventoryDto.getCode());
            goodsDeliver.put("HYCweight", inventoryDto.getPriuserdefdecm6()); // 产品实际重量
            goodsDeliver.put("HYCsize", inventoryDto.getPriuserdefdecm7()); // 产品体积重量

            goods.setGoodsDeliver(JSON.toJSONString(goodsDeliver));

            if (CollectionUtil.isNotEmpty(inventoryDto.getOssImageList())) {
                // 构图片JSON - 保留现有字段，只更新T+同步的字段
                Map<String, Object> goodsPic = new HashMap<>();

                // 如果是更新操作，先获取现有的图片JSON数据
                if (existingGoods != null && existingGoods.getGoodsPic() != null) {
                    try {
                        String exitingGoodsPicStr = existingGoods.getGoodsPic().toString();
                        if (oConvertUtils.isNotEmpty(exitingGoodsPicStr)) {
                            goodsPic.putAll(JSON.parseObject(exitingGoodsPicStr));
                        }
                    } catch (Exception e) {
                        log.warn("解析现有商品图片JSON失败，将创建新的JSON: {}", e.getMessage());
                    }
                }

                goodsPic.put("id", goods.getId());
                goodsPic.put("goodsCode", inventoryDto.getCode());

                // 简图（封面图）合并逻辑：
                // - 如果原有简图为空，则使用本次获取到的图片
                // - 如果原有简图不为空，则只追加新增的图片
                // - 多张图片用逗号","分隔，且去重
                // 获取现有简图集合
                java.util.LinkedHashSet<String> existingCoverSet = new java.util.LinkedHashSet<>();
                Object existingCoverObj = goodsPic.get("coverPic");
                if (existingCoverObj != null) {
                    String existingCoverStr = existingCoverObj.toString();
                    if (existingCoverStr != null && !existingCoverStr.trim().isEmpty()) {
                        String[] parts = existingCoverStr.split(",");
                        for (String p : parts) {
                            if (p != null) {
                                String tp = p.trim();
                                if (!tp.isEmpty()) {
                                    existingCoverSet.add(tp);
                                }
                            }
                        }
                    }
                }

                // 从本次T+同步数据中提取图片URL集合
                java.util.List<String> newUrls = new java.util.ArrayList<>();
                for (InventoryQueryRepDto.OssImageList oss : inventoryDto.getOssImageList()) {
                    if (oss != null && oss.getImageUrl() != null) {
                        String url = oss.getImageUrl().trim();
                        if (!url.isEmpty()) {
                            newUrls.add(url);
                        }
                    }
                }

                // 合并（只增不减，保持顺序，去重）
                java.util.LinkedHashSet<String> merged = new java.util.LinkedHashSet<>(existingCoverSet);
                for (String url : newUrls) {
                    merged.add(url);
                }

                // 设置合并后的简图字符串（逗号分隔）
                String mergedCoverPic = String.join(",", merged);
                goodsPic.put("coverPic", mergedCoverPic);

                goods.setGoodsPic(JSON.toJSONString(goodsPic));
            }

            // 设置商品状态为正常
            goods.setGoodsStatus("1");

            // 保存或更新商品
            return this.saveOrUpdate(goods);

        } catch (Exception e) {
            log.error("保存T+存货信息到商品表失败: {}", e.getMessage(), e);
            return false;
        }
    }

    /**
     * 重写save方法，添加T+系统同步
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Goods saveEntity(Goods entity) {
        boolean result = super.save(entity);
        if (result) {
            try {
                // 同步到T+系统
                InventoryInfoReqDto inventoryInfoReqDto = convertGoodsToInventoryInfo(entity, entity);
                // tplusService.inventoryCreate(inventoryInfoReqDto);
                // updateInventoryImage(entity, entity);
                log.info("商品新增同步到T+系统成功，商品编码: {}", entity.getGoodsCode());
            } catch (Exception e) {
                log.error("商品新增同步到T+系统失败，商品编码: {}, 错误信息: {}", entity.getGoodsCode(), e.getMessage(), e);
                // 这里可以选择是否回滚本地操作，根据业务需求决定
                throw new JeecgBootException(e.getMessage());
            }
        }
        return entity;
    }

    /**
     * 重写updateById方法，添加T+系统同步
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Goods updateEntityById(Goods entity) {
        Goods good = this.getById(entity.getId());
        boolean result = super.updateById(entity);
        if (result) {
            try {
                // 同步到T+系统
                InventoryInfoReqDto inventoryInfoReqDto = convertGoodsToInventoryInfo(entity, good);
                // tplusService.inventoryUpdate(inventoryInfoReqDto);
                // updateInventoryImage(entity, good);
                log.info("商品修改同步到T+系统成功，商品编码: {}", entity.getGoodsCode());
            } catch (Exception e) {
                log.error("商品修改同步到T+系统失败，商品编码: {}, 错误信息: {}", entity.getGoodsCode(), e.getMessage(), e);
                // 这里可以选择是否回滚本地操作，根据业务需求决定
                throw new JeecgBootException(e.getMessage());
            }
        }
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleGoodsPic(EbizGoods ebizGoods) {
        QueryWrapper<EbizGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(ebizGoods.getGoodsCode()), "goods_code", ebizGoods.getGoodsCode());
        List<EbizGoods> ebizGoodsPics = ebizGoodsService.list(queryWrapper);
        log.info("网站产品数据，商品编码: {}", ebizGoodsPics.size());
        for (EbizGoods ebizGoodsPic : ebizGoodsPics) {
            QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
            goodsQueryWrapper.eq("goods_code", ebizGoodsPic.getGoodsCode());
            Goods good = this.getOne(goodsQueryWrapper);
            if (good != null) {
                updateInventoryImage(ebizGoodsPic, good);
            }
        }
    }

    private void updateInventoryImage(EbizGoods good, Goods goods) {
        try {
            Map<String, Object> goodsPic = new HashMap<>();
            // 解析现有JSON或初始化
            if (goods.getGoodsPic() != null) {
                try {
                    String existing = goods.getGoodsPic().toString();
                    if (oConvertUtils.isNotEmpty(existing)) {
                        goodsPic.putAll(JSON.parseObject(existing));
                    }
                } catch (Exception e) {
                    log.warn("解析商品图片JSON失败，使用新JSON: {}", e.getMessage());
                }
            }

            // 基础字段（始终补齐）
            goodsPic.put("id", goods.getId());
            String goodsCode = goods.getGoodsCode();
            if (goodsCode == null || goodsCode.trim().isEmpty()) {
                goodsCode = good != null ? good.getGoodsCode() : null;
            }
            goodsPic.put("goodsCode", goodsCode);

            // 合并封面图 coverPic（支持逗号分隔、只增不减、去重）
            java.util.LinkedHashSet<String> coverSet = new java.util.LinkedHashSet<>();
            Object existingCoverObj = goodsPic.get("coverPic");
            if (existingCoverObj != null) {
                String ec = existingCoverObj.toString();
                if (ec != null && !ec.trim().isEmpty()) {
                    String[] parts = ec.split(",");
                    for (String p : parts) {
                        if (p != null) {
                            String tp = p.trim();
                            if (!tp.isEmpty()) {
                                coverSet.add(tp);
                            }
                        }
                    }
                }
            }
            if (good != null && good.getCoverPic() != null) {
                String cp = good.getCoverPic().trim();
                if (!cp.isEmpty()) {
                    String[] parts = cp.split(",");
                    for (String p : parts) {
                        if (p != null) {
                            String tp = p.trim();
                            if (!tp.isEmpty()) {
                                coverSet.add(tp);
                            }
                        }
                    }
                }
            }
            goodsPic.put("coverPic", String.join(",", coverSet));

            // 合并网站图 websitePic（支持逗号分隔、只增不减、去重）
            LinkedHashSet<String> websiteSet = new LinkedHashSet<>();
            Object existingWebsiteObj = goodsPic.get("websitePic");
            if (existingWebsiteObj != null) {
                String ew = existingWebsiteObj.toString();
                if (ew != null && !ew.trim().isEmpty()) {
                    String[] parts = ew.split(",");
                    for (String p : parts) {
                        if (p != null) {
                            String tp = p.trim();
                            if (!tp.isEmpty()) {
                                websiteSet.add(tp);
                            }
                        }
                    }
                }
            }
            if (good != null && good.getPics() != null) {
                String pics = good.getPics().trim();
                if (!pics.isEmpty()) {
                    String[] parts = pics.split(",");
                    for (String p : parts) {
                        if (p != null) {
                            String tp = p.trim();
                            if (!tp.isEmpty()) {
                                websiteSet.add(tp);
                            }
                        }
                    }
                }
            }
            goodsPic.put("websitePic", String.join(",", websiteSet));
            // 处理首页图片
            if (StringUtils.isBlank(goods.getCoverPic()) && CollectionUtil.isNotEmpty(coverSet)) {
                goods.setCoverPic(coverSet.stream().findFirst().orElse(null));
            }
            // 写回并持久化
            goods.setGoodsPic(JSON.toJSONString(goodsPic));
            this.updateById(goods);
        } catch (Exception e) {
            log.error("合并商品图片失败，商品编码: {}, 错误: {}", goods.getGoodsCode(), e.getMessage(), e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handlePlusGoodsPic(EbizGoods ebizGoods, List<Map<String, Object>> list, List<Map<String, Object>> picList) {
        List<EbizGoods> ebizGoodsPics = new ArrayList<>();
        /*Map<String,String> picMap = new HashMap<>();
        if(CollectionUtil.isNotEmpty(picList)){
            picMap = picList.stream().collect(Collectors.toMap(m -> m.get("code").toString(), m -> m.get("imageFile").toString()));
        }*/
        for (Map<String, Object> map : list) {
            if (map.get("imageFile") != null) {
                String pics = map.get("imageFile").toString();
                java.util.LinkedHashSet<String> picSet = new java.util.LinkedHashSet<>();
                String[] picArray = pics.split(";");
                for (String pic : picArray) {
                    if (pic != null && !pic.trim().isEmpty()) {
                        String goodsCode = map.get("code").toString();
                        String externalUrl = INVENTORY_IMAGE_URL+pic.replace(":default","").trim();
                        try {
                            byte[] imageBytes = downloadBytes(externalUrl);
                            String fileName = extractFileName(pic.replace(":default","").trim());
                            String key = buildS3Key(goodsCode, fileName);
                            String contentType = guessContentType(fileName);
                            s3Util.uploadPublicFile(key, imageBytes, contentType);
                            String s3Url = s3Util.getFileUrl(key);
                            OssFile ossFile = new OssFile();
                            ossFile.setFileName(CommonUtils.getFileName(fileName));
                            ossFile.setFileType("coverPic");
                            ossFile.setSuffix(Objects.requireNonNull(fileName)
                                    .substring(fileName.lastIndexOf(".") + 1));
                            ossFile.setUrl(s3Url);
                            ossFile.setStorageType("s3");
                            ossFile.setBusinessId(goodsCode);
                            ossFileService.save(ossFile);
                            picSet.add(s3Url);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            log.warn("上传图片到S3失败，商品编码: {}，图片: {}，错误: {}", goodsCode, externalUrl, ex.getMessage());
                        }
                    }
                }
                EbizGoods ebizGoodsEntity = new EbizGoods();
                ebizGoodsEntity.setGoodsCode(map.get("code").toString());
                ebizGoodsEntity.setCoverPic(String.join(",", picSet));
                ebizGoodsPics.add(ebizGoodsEntity);
            }

        }
        log.info("网站产品数据，商品编码: {}", ebizGoodsPics.size());
        for (EbizGoods ebizGoodsPic : ebizGoodsPics) {
            QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
            goodsQueryWrapper.eq("goods_code", ebizGoodsPic.getGoodsCode());
            Goods good = this.getOne(goodsQueryWrapper);
            if (good != null) {
                updateInventoryImage(ebizGoodsPic, good);
            }
        }
    }

    private String buildS3Key(String goodsCode, String fileName) {
        String safeCode = goodsCode == null ? "unknown" : goodsCode.trim();
        return "goods/" + safeCode + "/" + fileName;
    }

    private String extractFileName(String path) {
        if (path == null || path.trim().isEmpty()) {
            return UUIDGenerator.generate() + ".jpg";
        }
        String p = path.trim();
        int qIndex = p.indexOf('?');
        if (qIndex >= 0) {
            p = p.substring(0, qIndex);
        }
        int lastSlash = Math.max(p.lastIndexOf('/'), p.lastIndexOf('\\'));
        String name = lastSlash >= 0 ? p.substring(lastSlash + 1) : p;
        if (name.isEmpty()) {
            name = UUIDGenerator.generate() + ".jpg";
        }
        return name;
    }

    private String guessContentType(String fileName) {
        String lower = fileName == null ? "" : fileName.toLowerCase();
        if (lower.endsWith(".png"))
            return "image/png";
        if (lower.endsWith(".gif"))
            return "image/gif";
        if (lower.endsWith(".webp"))
            return "image/webp";
        if (lower.endsWith(".bmp"))
            return "image/bmp";
        if (lower.endsWith(".jpeg") || lower.endsWith(".jpg"))
            return "image/jpeg";
        return "application/octet-stream";
    }

    private byte[] downloadBytes(String url) throws Exception {
        java.net.URL u = new java.net.URL(url);
        try (java.io.InputStream in = u.openStream();
                java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream()) {
            byte[] buffer = new byte[8192];
            int read;
            while ((read = in.read(buffer)) != -1) {
                baos.write(buffer, 0, read);
            }
            return baos.toByteArray();
        }
    }

    /**
     * 将Goods对象转换为InventoryInfoReqDto
     *
     * @param goods 商品信息
     * @return T+存货信息请求对象
     */
    private InventoryInfoReqDto convertGoodsToInventoryInfo(Goods goods, Goods good) {
        InventoryInfoReqDto inventoryInfoReqDto = new InventoryInfoReqDto();
        InventoryEntityReqDto inventoryEntityReqDto = new InventoryEntityReqDto();
        // 处理动态属性（自定义项和自由项）
        List<String> dynamicKeys = new ArrayList<>();
        List<Object> dynamicValues = new ArrayList<>();
        // 基本信息映射
        inventoryEntityReqDto.setCode(good.getGoodsCode());
        inventoryEntityReqDto.setName(good.getGoodsName());

        // 供应情况字典转换
        if (goods.getSupplySituation() != null) {
            String supplySituationName = getDictTextByValue("GYQK", goods.getSupplySituation());
            dynamicKeys.add("priuserdefnvc11");
            dynamicValues.add(supplySituationName);
        }

        // 适配品牌字典转换
        /*
         * if (goods.getGoodsBrand() != null) {
         * String brandName = getDictTextByValue("XFPP", goods.getGoodsBrand());
         * dynamicKeys.add("priuserdefnvc6");
         * dynamicValues.add(brandName);
         * }
         */

        // 中文简称（从产品中文名称映射）
        if (goods.getGoodsNameCn() != null) {
            dynamicKeys.add("priuserdefnvc1");
            dynamicValues.add(goods.getGoodsNameCn());
        }

        // 存货描述（从产品描述映射）
        if (goods.getGoodsDescribe() != null) {
            inventoryEntityReqDto.setInventoryDescript(goods.getGoodsDescribe());
        }

        // 从goodsInfo JSON中提取信息
        if (goods.getGoodsInfo() != null) {
            try {
                Map<String, Object> goodsInfoMap = JSON.parseObject(goods.getGoodsInfo().toString(), Map.class);

                // 存货属性设置
                // 电商属性
                if (goodsInfoMap.containsKey("isEshop")) {
                    String isEshop = (String) goodsInfoMap.get("isEshop");
                    if (isEshop != null && !isEshop.trim().isEmpty()) {
                        inventoryEntityReqDto.setIsEshop(isEshop); // 电商属性
                    }
                }
                // 外购属性
                if (goodsInfoMap.containsKey("isPurchase")) {
                    String isPurchase = (String) goodsInfoMap.get("isPurchase");
                    if (isPurchase != null && !isPurchase.trim().isEmpty()) {
                        inventoryEntityReqDto.setIsPurchase(isPurchase); // 外购属性
                    }
                }
                // 销售属性
                if (goodsInfoMap.containsKey("isSale")) {
                    String isSale = (String) goodsInfoMap.get("isSale");
                    if (isSale != null && !isSale.trim().isEmpty()) {
                        inventoryEntityReqDto.setIsSale(isSale); // 销售属性
                    }
                }
                // 自制属性
                if (goodsInfoMap.containsKey("isMadeSelf")) {
                    String isMadeSelf = (String) goodsInfoMap.get("isMadeSelf");
                    if (isMadeSelf != null && !isMadeSelf.trim().isEmpty()) {
                        inventoryEntityReqDto.setIsMadeSelf(isMadeSelf); // 自制属性
                    }
                }
                // 生产耗用属性
                if (goodsInfoMap.containsKey("isMaterial")) {
                    String isMaterial = (String) goodsInfoMap.get("isMaterial");
                    if (isMaterial != null && !isMaterial.trim().isEmpty()) {
                        inventoryEntityReqDto.setIsMaterial(isMaterial); // 生产耗用
                    }
                }
                // 人工成本属性
                if (goodsInfoMap.containsKey("isLaborCost")) {
                    String isLaborCost = (String) goodsInfoMap.get("isLaborCost");
                    if (isLaborCost != null && !isLaborCost.trim().isEmpty()) {
                        inventoryEntityReqDto.setIsLaborCost(isLaborCost); // 人工成本属性
                    }
                }
                // 委外属性
                if (goodsInfoMap.containsKey("isMadeRequest")) {
                    String isMadeRequest = (String) goodsInfoMap.get("isMadeRequest");
                    if (isMadeRequest != null && !isMadeRequest.trim().isEmpty()) {
                        inventoryEntityReqDto.setIsMadeRequest(isMadeRequest); // 委外属性
                    }
                }
                // 计价方式（默认设置为全月平均法）
                if (goodsInfoMap.containsKey("valueType")) {
                    String valueTypeCode = (String) goodsInfoMap.get("valueType");
                    if (valueTypeCode != null && !valueTypeCode.trim().isEmpty()) {
                        InventoryEntityReqDto.ValueType valueType = new InventoryEntityReqDto.ValueType();
                        valueType.setCode(valueTypeCode);
                        inventoryEntityReqDto.setValueType(valueType);
                    }
                }

                // 计量单位
                if (goodsInfoMap.containsKey("goodsUnit")) {
                    InventoryEntityReqDto.Unit unit = new InventoryEntityReqDto.Unit();

                    String goodsUnit = (String) goodsInfoMap.get("goodsUnit");
                    String goodsUnitName = getDictTextByValue("DW", goodsUnit);
                    unit.setCode(goodsUnit);
                    unit.setName(goodsUnitName);
                    inventoryEntityReqDto.setUnit(unit);
                }

                // 助记码
                if (goodsInfoMap.containsKey("shorthand")) {
                    inventoryEntityReqDto.setShorthand((String) goodsInfoMap.get("shorthand"));
                }

                // 二级分类
                if (goodsInfoMap.containsKey("categoryId_children")) {
                    String categoryId_childrenCode = (String) goodsInfoMap.get("categoryId_children");
                    String categoryId_childrenName = getDictTextByValue("EJFL", categoryId_childrenCode);
                    dynamicKeys.add("priuserdefnvc3");
                    dynamicValues.add(categoryId_childrenName);
                }

                // 包装（需要字典转换）
                if (goodsInfoMap.containsKey("packaging")) {
                    String packagingCode = (String) goodsInfoMap.get("packaging");
                    String packagingName = getDictTextByValue("SF", packagingCode);
                    dynamicKeys.add("priuserdefnvc4");
                    dynamicValues.add(packagingName);
                }

                // 质量（需要字典转换）
                if (goodsInfoMap.containsKey("quality")) {
                    String qualityCode = (String) goodsInfoMap.get("quality");
                    String qualityName = getDictTextByValue("ZL", qualityCode);
                    dynamicKeys.add("priuserdefnvc9");
                    dynamicValues.add(qualityName);
                }

                // 材质/细分品牌（需要字典转换）
                if (goodsInfoMap.containsKey("productMaterial")) {
                    String materialCode = (String) goodsInfoMap.get("productMaterial");
                    String materialName = getDictTextByValue("XFPP", materialCode);
                    dynamicKeys.add("priuserdefnvc10");
                    dynamicValues.add(materialName);
                }

                // 型号+适用品牌
                if (goodsInfoMap.containsKey("compatibleBrand")) {
                    String modelCode = (String) goodsInfoMap.get("compatibleBrand");
                    SysCategory sysCategory = sysCategoryService.getById(modelCode);
                    if (sysCategory != null) {
                        String modelName = sysCategory.getName();
                        // 型号
                        dynamicKeys.add("priuserdefnvc7");
                        dynamicValues.add(modelName);
                        SysCategory parentCategory = sysCategoryService.getById(sysCategory.getPid());
                        if (parentCategory != null) {
                            String parentCategoryName = parentCategory.getName();
                            // 适用品牌
                            dynamicKeys.add("priuserdefnvc6");
                            dynamicValues.add(parentCategoryName);
                        }
                    }
                }

                // 性质（需要字典转换）
                if (goodsInfoMap.containsKey("infringementRisk")) {
                    String attributesCode = (String) goodsInfoMap.get("infringementRisk");
                    String attributesName = getDictTextByValue("XZ", attributesCode);
                    dynamicKeys.add("priuserdefnvc8");
                    dynamicValues.add(attributesName);
                }

                // 二级分类
                if (goodsInfoMap.containsKey("categoryId_children")) {
                    String categoryId_childrenCode = (String) goodsInfoMap.get("categoryId_children");
                    String categoryId_childrenName = getDictTextByValue("EJFL", categoryId_childrenCode);
                    dynamicKeys.add("priuserdefnvc3");
                    dynamicValues.add(categoryId_childrenName);
                }

                // 标签型号
                if (goodsInfoMap.containsKey("labelModel")) {
                    String labelModelCode = (String) goodsInfoMap.get("labelModel");
                    String labelModelName = getDictTextByValue("BQXH", labelModelCode);
                    dynamicKeys.add("priuserdefnvc12");
                    dynamicValues.add(labelModelName);
                }

                // 标签质量
                if (goodsInfoMap.containsKey("labelQuality")) {
                    String labelQualityCode = (String) goodsInfoMap.get("labelQuality");
                    String labelQualityName = getDictTextByValue("BQZL", labelQualityCode);
                    dynamicKeys.add("priuserdefnvc18");
                    dynamicValues.add(labelQualityName);
                }

            } catch (Exception e) {
                log.warn("解析商品信息JSON失败，商品编码: {}, 错误信息: {}", goods.getGoodsCode(), e.getMessage());
            }
        }

        // 从goodsPrice JSON中提取价格信息
        if (goods.getGoodsPrice() != null) {
            try {
                Map<String, Object> goodsPriceMap = JSON.parseObject(goods.getGoodsPrice().toString(), Map.class);

                // 大陆成本
                if (goodsPriceMap.containsKey("mainlandCost")) {
                    Object mainlandCost = goodsPriceMap.get("mainlandCost");
                    if (mainlandCost != null) {
                        dynamicKeys.add("priuserdefdecm1");
                        dynamicValues.add(mainlandCost.toString());
                    }
                }

                // 香港成本
                if (goodsPriceMap.containsKey("hkCost")) {
                    Object hongKongCost = goodsPriceMap.get("hkCost");
                    if (hongKongCost != null) {
                        dynamicKeys.add("priuserdefdecm2");
                        dynamicValues.add(hongKongCost.toString());
                    }
                }

                // 香港利润率
                if (goodsPriceMap.containsKey("hkProfitMargin")) {
                    Object hkProfitMargin = goodsPriceMap.get("hkProfitMargin");
                    if (hkProfitMargin != null) {
                        dynamicKeys.add("priuserdefdecm4");
                        dynamicValues.add(hkProfitMargin.toString());
                    }
                }

                // 大陆利润率
                if (goodsPriceMap.containsKey("MainlandProfitMargin")) {
                    Object profitMargin = goodsPriceMap.get("MainlandProfitMargin");
                    if (profitMargin != null) {
                        dynamicKeys.add("priuserdefdecm5");
                        dynamicValues.add(profitMargin.toString());
                    }
                }

                // 注释：采购价格字段priuserdefdecm3在InventoryEntityReqDto中不存在，暂时跳过
                // if (goodsPriceMap.containsKey("purchasePrice")) {
                // Object purchasePrice = goodsPriceMap.get("purchasePrice");
                // if (purchasePrice != null) {
                // inventoryEntityReqDto.setPriuserdefdecm3(new
                // java.math.BigDecimal(purchasePrice.toString()));
                // }
                // }

            } catch (Exception e) {
                log.warn("解析商品价格JSON失败，商品编码: {}, 错误信息: {}", goods.getGoodsCode(), e.getMessage());
            }
        }
        if (goods.getGoodsEnglish() != null) {
            try {
                Map<String, Object> goodsEnglishMap = JSON.parseObject(goods.getGoodsEnglish().toString(), Map.class);
                // 英文简称
                if (goodsEnglishMap.containsKey("englishShortName")) {
                    dynamicKeys.add("priuserdefnvc2");
                    dynamicValues.add((String) goodsEnglishMap.get("englishShortName"));
                }
                // 英文名称
                if (goodsEnglishMap.containsKey("englishName")) {
                    inventoryEntityReqDto.setSpecification((String) goodsEnglishMap.get("englishName"));
                }
            } catch (Exception e) {
                log.warn("解析商品扩展JSON失败，商品编码: {}, 错误信息: {}", goods.getGoodsCode(), e.getMessage());
            }
        }
        if (goods.getGoodsDeliver() != null) {
            try {
                Map<String, Object> goodsDeliverMap = JSON.parseObject(goods.getGoodsDeliver().toString(), Map.class);
                // 实际重量
                if (goodsDeliverMap.containsKey("actualWeight")) {
                    Object actualWeight = goodsDeliverMap.get("actualWeight");
                    if (actualWeight != null) {
                        dynamicKeys.add("priuserdefdecm6");
                        dynamicValues.add(actualWeight.toString());
                    }
                }

                // 体积重量
                if (goodsDeliverMap.containsKey("volumeWeight")) {
                    Object volumeWeight = goodsDeliverMap.get("volumeWeight");
                    if (volumeWeight != null) {
                        dynamicKeys.add("priuserdefdecm7");
                        dynamicValues.add(volumeWeight.toString());
                    }
                }
            } catch (Exception e) {
                log.warn("解析商品扩展JSON失败，商品编码: {}, 错误信息: {}", goods.getGoodsCode(), e.getMessage());
            }
        }
        // 从goodsExtend JSON中提取扩展信息
        if (goods.getGoodsExtend() != null) {
            try {
                Map<String, Object> goodsExtendMap = JSON.parseObject(goods.getGoodsExtend().toString(), Map.class);

                // 注释：以下字段在InventoryEntityReqDto中不存在，暂时跳过
                // 开发人员 - priuserdefnvc13不存在
                // 负责人 - priuserdefnvc14不存在
                // 采购人员 - priuserdefnvc15不存在
                // 推荐指数 - priuserdefnvc16不存在
                // 商品来源 - priuserdefnvc17不存在
                // 开发类型 - priuserdefnvc19不存在
                // 关键词 - priuserdefnvc20不存在

            } catch (Exception e) {
                log.warn("解析商品扩展JSON失败，商品编码: {}, 错误信息: {}", goods.getGoodsCode(), e.getMessage());
            }
        }

        // 注释：以下直接字段映射在InventoryEntityReqDto中不存在，暂时跳过
        // 开发人员 - priuserdefnvc13不存在
        // 负责人 - priuserdefnvc14不存在
        // 采购人员 - priuserdefnvc15不存在
        // 推荐指数 - priuserdefnvc16不存在
        // 商品来源 - priuserdefnvc17不存在
        // 开发类型 - priuserdefnvc19不存在
        // 关键词 - priuserdefnvc20不存在

        // 含电或含液
        if (goods.getGoodsLogistics() != null) {
            String goodsLogistics = getDictTextByValue("HDHHY", goods.getGoodsLogistics());
            dynamicKeys.add("priuserdefnvc5");
            dynamicValues.add(goodsLogistics);
        }

        // 分类信息
        if (goods.getCategoryId() != null) {
            InventoryEntityReqDto.InventoryClass inventoryClass = new InventoryEntityReqDto.InventoryClass();
            inventoryClass.setCode(goods.getCategoryId());
            inventoryEntityReqDto.setInventoryClass(inventoryClass);
        }

        // 从goodsDeliver JSON中提取仓库信息
        if (goods.getGoodsInfo() != null) {
            try {
                Map<String, Object> goodsDeliverMap = JSON.parseObject(goods.getGoodsInfo().toString(), Map.class);

                // 默认仓库
                if (goodsDeliverMap.containsKey("defaultWarehouse")) {
                    InventoryEntityReqDto.Warehouse warehouse = new InventoryEntityReqDto.Warehouse();
                    warehouse.setCode((String) goodsDeliverMap.get("defaultWarehouse_code"));
                    inventoryEntityReqDto.setWarehouse(warehouse);
                }

                // 默认货位
                if (goodsDeliverMap.containsKey("defaultLocation")) {
                    InventoryEntityReqDto.InvLocation invLocation = new InventoryEntityReqDto.InvLocation();
                    invLocation.setCode((String) goodsDeliverMap.get("defaultLocation_code"));
                    inventoryEntityReqDto.setInvLocation(invLocation);
                }

                // 默认供应商
                // if (goodsDeliverMap.containsKey("defaultSupplier")) {
                // InventoryEntityReqDto.Partner partner = new InventoryEntityReqDto.Partner();
                // partner.setCode((String) goodsDeliverMap.get("defaultSupplier"));
                // inventoryEntityReqDto.setPartner(partner);
                // }

            } catch (Exception e) {
                log.warn("解析商品发货JSON失败，商品编码: {}, 错误信息: {}", goods.getGoodsCode(), e.getMessage());
            }
        }

        // 如果没有从goodsDeliver中获取到仓库信息，使用warehouseId字段
        if (inventoryEntityReqDto.getWarehouse() == null && goods.getWarehouseId() != null) {
            InventoryEntityReqDto.Warehouse warehouse = new InventoryEntityReqDto.Warehouse();
            warehouse.setCode(goods.getWarehouseId());
            inventoryEntityReqDto.setWarehouse(warehouse);
        }

        // 设置是否停用（根据商品状态判断）
        if (goods.getGoodsStatus() != null) {
            // 假设商品状态为"1"表示启用，"0"表示停用
            inventoryEntityReqDto.setDisabled("1".equals(goods.getGoodsStatus()) ? "false" : "true");
        } else {
            inventoryEntityReqDto.setDisabled("false"); // 默认启用
        }

        // 设置助记码（使用商品编码）
        if (goods.getGoodsCode() != null) {
            inventoryEntityReqDto.setShorthand(goods.getGoodsCode());
        }

        // 设置动态属性
        if (!dynamicKeys.isEmpty()) {
            inventoryEntityReqDto.setDynamicPropertyKeys(dynamicKeys.toArray());
            inventoryEntityReqDto.setDynamicPropertyValues(dynamicValues.toArray());
        }

        // 备注：以下字段已完成映射
        // - 基本信息：code, name, specification, valueType, imagefile
        // - 用户自定义字段：priuserdefnvc1-12, priuserdefnvc18
        // - 数值字段：priuserdefdecm1, priuserdefdecm2, priuserdefdecm4-7
        // - 复杂对象：Unit, InventoryClass, Warehouse, InvLocation, Partner, ProductInfo
        // - 属性字段：isEshop, isPurchase, isSale等
        // - 其他字段：inventoryDescript, createdtime, madeRecordDate, disabled, shorthand
        // - 动态属性：dynamicPropertyKeys, dynamicPropertyValues（包含开发人员、负责人、采购人员等自定义项）

        log.info("完成商品到存货信息的转换，商品编码: {}, 商品名称: {}, 动态属性数量: {}", goods.getGoodsCode(), goods.getGoodsName(),
                dynamicKeys.size());

        inventoryInfoReqDto.setInventoryEntityReqDto(inventoryEntityReqDto);
        return inventoryInfoReqDto;
    }

    /**
     * 通过字典文本获取字典编码
     *
     * @param dictCode 字典编码
     * @param text     字典文本
     * @return 字典值，如果未找到则返回原文本
     */
    private String getDictValueByText(String dictCode, String text) {
        if (oConvertUtils.isEmpty(text)) {
            return text;
        }

        try {
            List<DictModel> dictItems = sysDictService.queryDictItemsByCode(dictCode);
            if (dictItems != null && !dictItems.isEmpty()) {
                for (DictModel dictItem : dictItems) {
                    if (text.equals(dictItem.getText())) {
                        return dictItem.getValue();
                    }
                }
            }
        } catch (Exception e) {
            log.error("获取字典编码失败，dictCode: {}, text: {}", dictCode, text, e);
        }

        // 如果未找到匹配的字典项，返回原文本
        return text;
    }

    /**
     * 通过字典值获取字典文本
     *
     * @param dictCode 字典编码
     * @param value    字典值
     * @return 字典文本
     */
    private String getDictTextByValue(String dictCode, String value) {
        if (value == null || value.isEmpty()) {
            return null;
        }

        List<DictModel> dictList = sysDictService.queryDictItemsByCode(dictCode);
        if (dictList != null) {
            for (DictModel dictModel : dictList) {
                if (value.equals(dictModel.getValue())) {
                    return dictModel.getText();
                }
            }
        }
        return null;
    }

}
